<template>
	<view class="coupon-container">
		<!-- 状态筛选 -->
		<view class="status-filter">
			<view 
				class="filter-item" 
				:class="{ active: currentStatus === item.value }"
				v-for="item in statusList" 
				:key="item.value"
				@click="changeStatus(item.value)"
			>
				{{ item.label }}
			</view>
		</view>
		
		<!-- 优惠券列表 -->
		<view class="coupon-list">
			<view 
				class="coupon-item" 
				v-for="item in couponList" 
				:key="item.id"
				:class="{
					'disabled': item.status === 2 || item.status === 3,
					'discount-coupon': item.type === 2
				}"
				@click="handleCouponClick(item)">
			<view class="coupon-left">
				<view class="coupon-amount">
					<text v-if="item.type === 1" class="amount-symbol">¥</text>
					<text v-else class="amount-symbol">折</text>
					<text class="amount-value">
						{{ item.type === 1 ? item.minus : Math.round(item.discount) }}
					</text>
				</view>
				<view class="coupon-condition">
					{{ item.type === 1 ? `满${item.fullMoney}可用` : '全场可用' }}
				</view>
			</view>
			<view class="coupon-right">
				<view class="coupon-name">{{ item.name }}</view>
				<view class="coupon-desc">{{ item.details }}</view>
				<view class="coupon-time">
					有效期：{{ formatTime(item.expireTime) }}
				</view>
				<view class="coupon-status">
					<text v-if="item.status === 1" class="status-valid">可使用</text>
					<text v-else-if="item.status === 2" class="status-used">已使用</text>
					<text v-else class="status-expired">已过期</text>
				</view>
			</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="couponList.length === 0 && !loading">
			<image src="/static/images/empty-coupon.png" class="empty-image"></image>
			<text class="empty-text">暂无优惠券</text>
		</view>
		
		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && couponList.length > 0">
			<text @click="loadMore" :class="{ loading: loading }">
				{{ loading ? '加载中...' : '加载更多' }}
			</text>
		</view>
		
		<!-- 加载状态 -->
		<view class="loading-state" v-if="loading && couponList.length === 0">
			<text>加载中...</text>
		</view>
	</view>
</template>

<script>
// 只保留 getUserCouponList 导入
import { getUserCouponList } from '@/api/coupon'

export default {
  data() {
    return {
      currentStatus: 0, // 0-全部，1-可使用，2-已使用，3-已过期
      statusList: [
        { label: '全部', value: 0 },
        { label: '可使用', value: 1 },
        { label: '已使用', value: 2 },
        { label: '已过期', value: 3 }
      ],
      couponList: [],
      page: 1,
      pageSize: 10,
      hasMore: true,
      loading: false
    };
  },
  onLoad() {
    this.getCouponList();
  },
  onPullDownRefresh() {
    this.refresh();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },
  methods: {
    // 切换状态筛选
    changeStatus(status) {
      this.currentStatus = status;
      this.page = 1;
      this.couponList = [];
      this.hasMore = true;
      this.getCouponList();
    },
    
    // 获取优惠券列表
    async getCouponList() {
      if (this.loading) return;
    
      this.loading = true;
      try {
        const params = {
          pageNum: this.page,
          pageSize: this.pageSize,
          status: this.currentStatus === 0 ? null : this.currentStatus,
          type: null // 添加类型筛选参数，null表示获取所有类型
        };
    
        console.log('请求参数:', params);
    
        const response = await getUserCouponList(params);
        console.log('API响应:', response);
    
        if (response.code === 200) {
          const newList = response.rows || [];
          console.log('优惠券数据:', newList); // 打印数据，检查是否包含折扣券
    
          if (this.page === 1) {
            this.couponList = newList;
          } else {
            this.couponList = [...this.couponList, ...newList];
          }
    
          this.hasMore = newList.length === this.pageSize;
        } else {
          uni.showToast({
            title: response.msg || '获取优惠券失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取优惠券列表失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },
    
    // 刷新
    refresh() {
      this.page = 1;
      this.couponList = [];
      this.hasMore = true;
      this.getCouponList();
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++;
        this.getCouponList();
      }
    },
    
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    
    // 处理优惠券点击
    handleCouponClick(coupon) {
      // 跳转到详情页面
      uni.navigateTo({
        url: '/pages/mine/coupon/detail?id=' + coupon.id
      });
    },
    

    
    // 使用优惠券
    async useCoupon(couponId, orderId) {
      try {
        const response = await useCoupon({
          couponId: couponId,
          orderId: orderId
        });
        
        if (response.code === 200) {
          uni.showToast({
            title: '优惠券使用成功',
            icon: 'success'
          });
          // 刷新列表
          this.refresh();
        } else {
          uni.showToast({
            title: response.msg || '使用优惠券失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('使用优惠券失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    },
    
    // 删除优惠券
    async deleteCoupon(couponId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张优惠券吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await deleteCoupon(couponId);
              
              if (response.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 刷新列表
                this.refresh();
              } else {
                uni.showToast({
                  title: response.msg || '删除失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('删除优惠券失败:', error);
              uni.showToast({
                title: '网络错误，请重试',
                icon: 'none'
              });
            }
          }
        }
      });
    }
    // 删除使用优惠券和删除优惠券的方法（如果不需要可以删除）
  }
}
</script>

<style lang="scss">
.coupon-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	
	.status-filter {
		display: flex;
		background-color: #ffffff;
		padding: 20rpx 30rpx;
		margin-bottom: 20rpx;
		
		.filter-item {
			flex: 1;
			text-align: center;
			padding: 15rpx 0;
			font-size: 28rpx;
			color: #666;
			position: relative;
			
			&.active {
				color: #ff6b35;
				font-weight: bold;
				
				&::after {
					content: '';
					position: absolute;
					bottom: -20rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background-color: #ff6b35;
					border-radius: 2rpx;
				}
			}
		}
	}
	
	.coupon-list {
		padding: 0 30rpx;
		
		.coupon-item {
			display: flex;
			background: linear-gradient(135deg, #ff6b35 0%, #ff8c42 100%);
			border-radius: 20rpx;
			margin-bottom: 20rpx;
			overflow: hidden;
			position: relative;
			transition: transform 0.2s ease;
			
			&.discount-coupon {
				background: linear-gradient(135deg, #4285f4 0%, #5b9af5 100%);
			}
			
			&:active {
				transform: scale(0.98);
			}
			
			&.disabled {
				background: linear-gradient(135deg, #ccc 0%, #ddd 100%);
				
				&::before {
					content: '';
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background-color: rgba(0, 0, 0, 0.1);
					z-index: 1;
				}
			}
			
			.coupon-left {
				width: 200rpx;
				background-color: rgba(255, 255, 255, 0.1);
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 30rpx 20rpx;
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					right: -10rpx;
					top: 50%;
					transform: translateY(-50%);
					width: 20rpx;
					height: 20rpx;
					background-color: #f5f5f5;
					border-radius: 50%;
				}
				
				.coupon-amount {
					display: flex;
					align-items: baseline;
					
					.amount-symbol {
						font-size: 32rpx;
						color: #ffffff;
						font-weight: bold;
					}
					
					.amount-value {
						font-size: 60rpx;
						color: #ffffff;
						font-weight: bold;
						line-height: 1;
					}
				}
				
				.coupon-condition {
					font-size: 24rpx;
					color: #ffffff;
					margin-top: 10rpx;
					opacity: 0.9;
				}
			}
			
			.coupon-right {
				flex: 1;
				padding: 30rpx;
				background-color: #ffffff;
				
				.coupon-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 10rpx;
				}
				
				.coupon-desc {
					font-size: 26rpx;
					color: #666;
					margin-bottom: 15rpx;
					line-height: 1.4;
				}
				
				.coupon-time {
					font-size: 24rpx;
					color: #999;
					margin-bottom: 15rpx;
				}
				
				.coupon-status {
					text-align: right;
					
					.status-valid {
						display: inline-block;
						padding: 8rpx 20rpx;
						background-color: #ff6b35;
						color: #ffffff;
						font-size: 24rpx;
						border-radius: 20rpx;
					}
					
					.status-used {
						display: inline-block;
						padding: 8rpx 20rpx;
						background-color: #ccc;
						color: #ffffff;
						font-size: 24rpx;
						border-radius: 20rpx;
					}
					
					.status-expired {
						display: inline-block;
						padding: 8rpx 20rpx;
						background-color: #999;
						color: #ffffff;
						font-size: 24rpx;
						border-radius: 20rpx;
					}
				}
			}
		}
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		
		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 30rpx;
			opacity: 0.5;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.load-more {
		text-align: center;
		padding: 30rpx;
		
		text {
			font-size: 28rpx;
			color: #666;
			
			&.loading {
				color: #999;
			}
		}
	}
	
	.loading-state {
		text-align: center;
		padding: 100rpx 0;
		
		text {
			font-size: 28rpx;
			color: #999;
		}
	}
}
</style>
